package edu.sdjzu.filter;

import edu.sdjzu.config.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

import static org.springframework.http.HttpMethod.*;

@Component
public class JwtAuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtUtils jwtUtils; // 你自定义的工具类

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        if (!path.startsWith("/content/")) {
            return chain.filter(exchange); // 不拦截
        }


        if (exchange.getRequest().getMethod() == GET && path.startsWith("/content/articles")) {
            // 查询操作，放行
            return chain.filter(exchange);
        }

        String authHeader = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.hasText(authHeader) && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            System.out.println("提取的 token: " + token);

            try {
                System.out.println("開始解析 token...");
                Claims claims = jwtUtils.parseToken(token);
                System.out.println("解析結果: " + claims);
                System.out.println("userId: " + claims.get("userId"));
                System.out.println("username: " + claims.get("username"));
                return chain.filter(exchange);
            } catch (Exception e) {
                System.out.println("Token 解析失敗，錯誤信息: " + e.getMessage());
                e.printStackTrace(); // 打印完整的堆棧跟踪
                return unauthorized(exchange, "Invalid JWT token");
            }
        } else {
            return unauthorized(exchange, "Missing JWT token");
        }
    }

    private Mono<Void> unauthorized(ServerWebExchange exchange, String message) {
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        exchange.getResponse().getHeaders().add("Content-Type", "application/json");
        byte[] bytes = ("{\"code\":401,\"msg\":\"" + message + "\"}").getBytes(StandardCharsets.UTF_8);
        return exchange.getResponse().writeWith(Mono.just(exchange.getResponse()
                .bufferFactory().wrap(bytes)));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
